//
//  MiaoYinTools.m
//  MiaoYin
//
//  Created by DarkWorld on 2019/12/11.
//  Copyright © 2019 Dark. All rights reserved.
//

#import "MiaoYinTools.h"
#import "AppDelegate.h"




@implementation MiaoYinTools
#pragma mark - 退出登录

/// 添加好友来源
/// @param state 值
NSString * NSStringFromAddFriendSource_Type(AddFriendSource_Type state) {
  switch (state) {
    case AddSource_Type_GROUP:
      return @"5";
          break;
    case AddSource_Type_SCAN:
      return @"4";
          break;
    case AddSource_Type_PHONE:
      return @"1";
          break;
    case AddSource_Type_MYIAOYIN:
      return @"2";
          break;
    case AddSource_Type_CARD:
      return @"6";
          break;
    case AddSource_Type_Near:
      return @"4";
          break;
  }
}

/// 添加好友来源UI展示数据
/// @param state  数据来源
NSString * ShowUIFromAddFriendSource_Type(NSString *state){
    if ([state isEqualToString:@"AddSource_Type_GROUP"]) {
        return @"通过群聊添加";
    }else if ([state isEqualToString:@"AddSource_Type_SCAN"]){
        return @"通过扫一扫添加";
    }
    else if ([state isEqualToString:@"AddSource_Type_PHONE"]){
        return @"通过手机号添加";
    }
    else if ([state isEqualToString:@"AddSource_Type_MYIAOYIN"]){
        return @"通过秒音号添加";
    }
    else if ([state isEqualToString:@"AddSource_Type_CARD"]){
        return @"通过名片分享添加";
    }
    else {
        return @"附近的人添加";
    }


}
/// 退出登录
+ (void)logout
{
    

}

/// 清除登录时候缓存本地的一些数据和一些跟账号绑定的缓存数据
+ (void)cleanLoginData
{
   


}
#pragma mark - 切换rootVC
/// 登录设置刷新rootVC
+ (void)setFreashRootVc
{
   

}

+ (void)setFreashRootVc2
{
   
  

}
/// 更新服务器设备token
+ (void)updateServerToken
{
    
}

#pragma mark - UIAlertController

/// 弹框
/// @param title 标题
/// @param message 内容
/// @param style 弹窗类型
/// @param actionTitles action标题数组
/// @param actionStyles  actions类型
/// @param target  调用者
/// @param handlers 回调
+ (void)alertWithTitle:(NSString * __nullable)title
     message:(NSString *__nullable)message
       style:(UIAlertControllerStyle)style
actionTitles:(NSArray *)actionTitles
actionStyles:(NSArray *)actionStyles
      target:(UIViewController *)target
    handlers:(void(^)(NSInteger index))handlers
{
    NSAssert(actionTitles.count == actionStyles.count, @"actionTitles和actionStyles要保持一致");
    kStartTime
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:style];
    
    for (int i = 0; i < actionTitles.count; i++) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:actionTitles[i] style:[actionStyles[i] integerValue] handler:^(UIAlertAction * _Nonnull action) {
            
            if (handlers) {
                handlers(i);
            }
        }];
        [alertController addAction:action];
    }
    kEndTime

    [target presentViewController:alertController animated:YES completion:nil];
}
#pragma mark - 关于数据转化的一些操作
// 给定字符串根据指定的个数进行分组，每一组用空格分隔

/// 银行卡转星号
/// @param string 银行卡
+ (NSString *)groupedBankString:(NSString *)string
{

    NSString *str = [string stringByReplacingOccurrencesOfString:@" " withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, string.length)];

    // 根据长度计算分组的个数
    NSInteger groupCount = (NSInteger)ceilf((CGFloat)str.length /4);
    NSMutableArray *components = [[NSMutableArray alloc] init];

    for (NSInteger i = 0; i < groupCount; i++) {
        if ((i*4 + 4) >= str.length) {
            [components addObject:[str substringFromIndex:i*4]];
        } else {
            NSString * secureStr = [str substringWithRange:NSMakeRange(i*4, 4)];
            secureStr = [secureStr stringByReplacingCharactersInRange:NSMakeRange(0, 4) withString:@"****"];
            [components addObject:secureStr];
        }
    }
    NSString *groupedString = [components componentsJoinedByString:@" "];
    return groupedString;
}


/// 证件数字转化星号
/// @param idNum 证件号码
+ (NSString *)idCardSuitScanf:(NSString *)idNum
{
    if(idNum&&idNum.length>8)
     {
         idNum = [NSString stringWithFormat:@"%@",idNum];
         for (int i = 4; i< idNum.length-4; i++) {
             idNum = [idNum stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:@"*"];
         }
         return idNum;
     }
     return idNum;
    
}
/**
 隐藏手机号中间几位为星号
 
 @param telNumber 手机号
 @return 返回隐藏为星号 的手机号
 */
+ (NSString *)numberSuitScanf:(NSString *)telNumber
{
    if(telNumber&&telNumber.length>7)
    {
        telNumber = [NSString stringWithFormat:@"%@",telNumber];
        NSString *numberString = [telNumber stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
        return numberString;
    }
   
    return telNumber;
}
//将字典转换成字符串 key=value&key=value&key=value
+ (NSString *)parseDictionaryToFormattedString:(NSDictionary *)paramsDic;
{
    NSMutableArray *tempArray = [NSMutableArray array];
    NSArray *keyArray = [paramsDic allKeys];
    for (NSString *key in keyArray) {
        NSString *valueString = [paramsDic objectForKey:key];
        NSString *formattedString = [NSString stringWithFormat:@"%@=%@", key, valueString];
        [tempArray addObject:formattedString];
    }
    NSString *finalString = [tempArray componentsJoinedByString:@"&"];
    return finalString;
}


/**
 *  json 转字典
 *
 *  @param jsonString json
 *
 *  @return 字典
 */
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    
    if (jsonString == nil) {
        
        return nil;
        
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *err;
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                         
                                                        options:NSJSONReadingMutableContainers
                         
                                                          error:&err];
    
    if(err) {
        
        DLog(@"json解析失败：%@",err);
        
        return nil;
        
    }
    
    return dic;
    
}

/**
 *  data 转字典
 *
 *  @param data data
 *
 *  @return 字典
 */
+ (NSDictionary *)dictionaryWithData:(NSData *)data
{
    //NSData-->NSDictionary
    NSDictionary *myDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    
    //NSData-->NSDictionary
    //    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    //    NSDictionary *myDictionary = [unarchiver decodeObjectForKey:@"KeyValue"];
    //    [unarchiver finishDecoding];
    
    return myDictionary;
}

/// 字典转data
/// @param dict 字典
+ (NSData *)dictionaryToJsonData:(NSDictionary *)dict
{
    // 转成Json数据
    if ([NSJSONSerialization isValidJSONObject:dict])
    {
        NSError *error = nil;
        NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
        if(error)
        {
            NSLog(@"[%@] Post Json Error", [self class]);
        }
        return data;
    }
    else
    {
        NSLog(@"[%@] Post Json is not valid", [self class]);
    }
    return nil;
}

/**
 *  字典 转 json
 *
 *  @param dic 字典
 *
 *  @return json
 */
+ (NSString *)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    NSString *jsonstring = [[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    //处理下url事件
    jsonstring = [jsonstring stringByReplacingOccurrencesOfString:@"\\" withString:@""];
    return jsonstring;
    
    
}

/**
 数组转json
 
 @param array 数组
 @return json
 */
+ (NSString*)arrayToJson:(NSArray *)array
{
    NSError *parseError = nil;

    NSData *data=[NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&parseError];
    NSString *jsonstring = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    //处理下url事件
    jsonstring = [jsonstring stringByReplacingOccurrencesOfString:@"\\" withString:@""];
    return jsonstring;
}
/**
 *  URLEncode
 */
+ (NSString *)URLEncodedString:(NSString *)tempString
{
    // CharactersToBeEscaped = @":/?&=;+!@#$()~',*";
    // CharactersToLeaveUnescaped = @"[].";
    
    NSString *unencodedString = tempString;
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)unencodedString,
                                                              NULL,
                                                              (CFStringRef)@"!$&'*+,/:;=?@~%#[]",
                                                              kCFStringEncodingUTF8));
//   平台转化问题  iOS转化空格有问题  iOS 转化成功%20  java转化成+
    encodedString = [encodedString stringByReplacingOccurrencesOfString:@"%20" withString:@"+"];
    //   平台转化问题  iOS转化-有问题  iOS 转化成功%2D java转化成-
    encodedString = [encodedString stringByReplacingOccurrencesOfString:@"%2D" withString:@"-"];
    encodedString = [encodedString stringByReplacingOccurrencesOfString:@"%0A" withString:@"\n"];

    return encodedString;
}
/**
 字符串转MD5
 
 @param string 字符串
 @return MD5值
 */
+ (NSString *)stringToMD5:(NSString *)string
{
    return [string qmui_md5];
}


+ (float)floatWithdecimalNumber:(double)num {
    return [[self decimalNumber:num] floatValue];
}

+ (double)doubleWithdecimalNumber:(double)num {
    return [[self decimalNumber:num] doubleValue];
}

+ (NSString *)stringWithDecimalNumber:(double)num {
    return [[self decimalNumber:num] stringValue];
}

+ (NSDecimalNumber *)decimalNumber:(double)num {
    NSString *numString = [NSString stringWithFormat:@"%lf", num];
    return [NSDecimalNumber decimalNumberWithString:numString];
}
#pragma mark - 时间相关处理

/// 获取当前月份
/// @param dataString 时间字符串
+ (NSString *)getMonthWithDateString:(NSString *)dataString
{
    //把字符串转为NSdate
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *timeDate = [dateFormatter dateFromString:dataString];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSCalendarUnitYear | //年
                            NSCalendarUnitMonth | //月份
                            NSCalendarUnitDay | //日
                            NSCalendarUnitHour |  //小时
                            NSCalendarUnitMinute |  //分钟
                            NSCalendarUnitSecond;  // 秒
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:timeDate];

    NSInteger year = [dateComponent year];
    NSInteger month = [dateComponent month];
    NSInteger day = [dateComponent day];
    NSInteger hour = [dateComponent hour];
    NSInteger minute = [dateComponent minute];
    NSInteger second = [dateComponent second];
    return [NSString stringWithFormat:@"%ld",month];
}

/// 判断两个时间是否是同一个月
/// @param time1 时间1
/// @param time2 时间2
+ (BOOL)isInSameMonth:(NSString *)time1 time2:(NSString *)time2
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date1 = [dateFormatter dateFromString:time1];
    NSDate *date2 = [dateFormatter dateFromString:time2];

    NSCalendar *calendar = [NSCalendar currentCalendar];
    int unit = NSCalendarUnitMonth | NSCalendarUnitYear;

    NSDateComponents *nowCmps = [calendar components:unit fromDate:date1];
    NSDateComponents *selfCmps = [calendar components:unit fromDate:date2];

    return (nowCmps.year == selfCmps.year)&&(nowCmps.month == selfCmps.month);
    
}
#pragma mark - 关于界面切换跳转

/// 跳转指定界面
/// @param vcName 跳转界面类名
/// @param currentVc 当前VC（可以为空，为空自动获取当前VC）
/// @param params 附带参数
+ (void)pushVCName:(NSString *)vcName
         currentVc:(nullable UIViewController *)currentVc
            params:(nullable NSDictionary*)params
{
    //先获取当前VC
    if (!currentVc) {
        currentVc = [self currentVC];
       
    }
    
    //然后在获取跳转VC
    const char *className = [vcName cStringUsingEncoding:NSASCIIStringEncoding];
    // 从一个字串返回一个类
    Class newClass = objc_getClass(className);
    UIViewController *instance;
    if (!newClass)
    {
       
        DLog(@"该%@不存在",vcName);
        return;
        // 创建一个类
               Class superClass = [NSObject class];
               newClass = objc_allocateClassPair(superClass, className, 0);
               // 注册你创建的这个类
               objc_registerClassPair(newClass);

    }
    else
    {
       instance = [[newClass alloc] init];
        instance.hidesBottomBarWhenPushed = YES;

    }
    // 创建对象
    
    //给对象赋值
    for (NSString *key in params.allKeys) {
        id value = params[key];
        if (value && ![value isKindOfClass:[NSNull class]]) {
            NSString *capital = [[key substringToIndex:1] uppercaseString];
            NSString *capitalizedKey  = [key stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:capital];
            SEL sel = NSSelectorFromString([NSString stringWithFormat:@"set%@:",capitalizedKey]);
            if ([instance respondsToSelector:sel]) {
                [instance setValue:value forKey:key];
            }
        }
    }


    
        //    离开就隐藏tabbar
        [currentVc.navigationController pushViewController:instance animated:YES];

   

}

/**
 返回多层
 
 @param count 层数
 @param navigationController 导航栏控制
 
 */
+ (void)navBackToCount:(NSInteger)count navigationController:(UINavigationController *)navigationController viewController:(UIViewController *)viewController
{
    NSInteger index = (NSInteger)[[navigationController viewControllers] indexOfObject:viewController];
    if (index > count) {
        [navigationController popToViewController:[navigationController.viewControllers objectAtIndex:(index-count)] animated:YES];
    }else{
        [navigationController popToRootViewControllerAnimated:YES];
    }
}


#pragma mark - 搜索

+ (BOOL)isContains:(NSString *)firstString withString:(NSString *)secondString
{
    if (firstString.length == 0 || secondString.length == 0) {
        return NO;
    }
    NSString *twoStr = [[secondString stringByReplacingOccurrencesOfString:@" " withString:@""] lowercaseString];
    if ([[firstString lowercaseString] containsString:[secondString lowercaseString]] ||
        [[firstString lowercaseString] containsString:twoStr] ||
        [[[self hanZiToPinYinWithString:firstString] lowercaseString] containsString:twoStr]) {
        return YES;
    }
    return NO;
}
/**
 *  汉字转拼音
 *
 *  @param hanZi 汉字
 *
 *  @return 转换后的拼音
 */
+ (NSString *)hanZiToPinYinWithString:(NSString *)hanZi {
    
    return @"";
}
+ (BOOL)isChinese:(NSString *)text {
    NSString *match = @"(^[\u4e00-\u9fa5]+$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:text];
}
#pragma mark - 关于系统权限问题

/**
 *  判断有无权限
 */
+ (BOOL)judgeAuthorization:(SystemAuthorities)systemAuthorities{
    
    
    return YES;
}
//提示弹框
+ (void)executeAlterTips:(NSString *)alterTips{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        NSString *alterContent = @"提示";
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:alterContent message:alterTips preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"去设置" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertController addAction:cancel];
        [alertController addAction:action];
        [[self currentVC] presentViewController:alertController animated:YES completion:nil];
    });
}
#pragma mark - 视频处理
/**
 获得视频信息
 */
+ (NSMutableDictionary *)getVideoInfoWith:(PHAsset *)videoAsset{
    
    /// 包含该视频的基础信息
    PHAssetResource * resource = [[PHAssetResource assetResourcesForAsset: videoAsset] firstObject];
    
    NSString *string1 = [resource.description stringByReplacingOccurrencesOfString:@"{" withString:@""];
    NSString *string2 = [string1 stringByReplacingOccurrencesOfString:@"}" withString:@""];
    NSString *string3 = [string2 stringByReplacingOccurrencesOfString:@", " withString:@","];
    NSMutableArray *resourceArray =  [NSMutableArray arrayWithArray:[string3 componentsSeparatedByString:@" "]];
    [resourceArray removeObjectAtIndex:0];
    [resourceArray removeObjectAtIndex:0];
    
    for (NSInteger index = 0; index<resourceArray.count; index++) {
        NSString *string = resourceArray[index];
        NSString *ret = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
        resourceArray[index] = ret;
    }
    
    NSMutableDictionary *videoInfo = [[NSMutableDictionary alloc] init];
    
    for (NSString *string in resourceArray) {
        NSArray *array = [string componentsSeparatedByString:@"="];
        videoInfo[array[0]] = array[1];
    }
    
    DLog(@"视频信息: %@",videoInfo);
    
    return videoInfo;
}

/**
 将视频转换为mp4格式
 */
+(void)convertVideoToMP4Format:(PHAsset *)videoAsset Compelete:(void(^)(NSURL *fileUrl))fileUrlHandler{
    if(!videoAsset)
    {
        return;
    }
    PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
    options.version = PHImageRequestOptionsVersionCurrent;
    options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
    
    PHImageManager *manager = [PHImageManager defaultManager];
    [manager requestAVAssetForVideo:videoAsset
                            options:options
                      resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
                          
                          [MiaoYinTools convertMovToMp4FromAVURLAsset:(AVURLAsset *)asset andCompeleteHandler:^(NSURL * _Nonnull fileUrl) {
                              
                              fileUrlHandler(fileUrl);
                          }];
                      }];
}

/**
 执行 将mov格式转化为mp4操作
 */
+ (void)convertMovToMp4FromAVURLAsset:(AVURLAsset*)urlAsset andCompeleteHandler:(void(^)(NSURL *fileUrl))fileUrlHandler{
    
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:urlAsset.URL options:nil];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    if ([compatiblePresets containsObject:AVAssetExportPresetLowQuality]) {
        
        //  在Documents目录下创建一个名为FileData的文件夹
        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"Cache/VideoData"];
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL isDir = FALSE;
        BOOL isDirExist = [fileManager fileExistsAtPath:path isDirectory:&isDir];
        if(!(isDirExist && isDir)) {
            BOOL bCreateDir = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
            if(!bCreateDir){
                NSLog(@"创建文件夹失败！%@",path);
            }
            NSLog(@"创建文件夹成功，文件路径%@",path);
        }
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
        [formatter setDateFormat:@"yyyy_MM_dd_HH_mm_ss"]; //每次启动后都保存一个新的日志文件中
        NSString *dateStr = [formatter stringFromDate:[NSDate date]];
        __block NSString *resultPath = [path stringByAppendingFormat:@"/%@.mp4",dateStr];
        
        NSLog(@"初始化转化为mp4后，文件地址:%@",resultPath);
        
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
        exportSession.outputURL = [NSURL fileURLWithPath:resultPath];
        exportSession.outputFileType = AVFileTypeMPEG4; //mp4
        exportSession.shouldOptimizeForNetworkUse = YES;
        
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            int exportStatus = exportSession.status;
            switch (exportStatus) {
                case AVAssetExportSessionStatusFailed:
                    NSLog(@"AVAssetExportSessionStatusFailed");
                    fileUrlHandler(nil);
                    break;
                case AVAssetExportSessionStatusCompleted:
                    NSLog(@"AVAssetExportSessionStatusCompleted");
                    fileUrlHandler(exportSession.outputURL);
                    break;
            }
        }];
    }
}

/// 通过phasset获取封面
/// @param asset phasset
/// @param resultBack block
+ (void)getVideoImageFromPHAsset:(PHAsset *)asset Complete:(void (^)(UIImage *image))resultBack
{
    
    PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
    option.resizeMode = PHImageRequestOptionsResizeModeFast;
    
    [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:CGSizeMake(200, 200) contentMode:PHImageContentModeDefault options:option resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        
        UIImage *iamge = result;
        resultBack(iamge);
    }];
}



#pragma mark - 短视频阿里数据处理字典数据获得sign
/// 获取阿里短视频模块数据处理的sign
/// @param dict 参数
+ (NSString *)getAliVideoSign:(NSDictionary *)dict
{
    /*请求参数按照参数名ASCII码从小到大排序*/
    NSArray *keys = [dict allKeys];
    //按字母顺序排序
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2)
    {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];

    NSString *returnStr = @"";

    //拼接字符串

    for (int i=0;i<sortedArray.count;i++){
        
         NSString *category = sortedArray[i];
        if (i==0) {
              returnStr =[NSString stringWithFormat:@"%@=%@",category,dict[category]];
        }else{
              returnStr = [NSString stringWithFormat:@"%@&%@=%@",returnStr,category,dict[category]];}
        }

    /*拼接上key得到stringSignTemp*/
    if (returnStr.length >0) {
        returnStr = [NSString stringWithFormat:@"%@&key=%@",returnStr,MYAliVideoKey];

    }
    else
    {
        returnStr = [NSString stringWithFormat:@"key=%@",MYAliVideoKey];

    }

    //urlencode
//    returnStr = [returnStr stringByURLEncode];
    /*md5加密*/
    returnStr = [returnStr stringToMD5];
    return returnStr;
}
#pragma mark - 其他
/// 跳转新年活动界面
+ (void)toNewYearActivtyVC:(UIViewController *)currentVC
{
    
     
    
}
+ (void)popGestureClose:(UIViewController *)VC
{
    // 禁用侧滑返回手势
    if ([VC.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        //这里对添加到右滑视图上的所有手势禁用
        for (UIGestureRecognizer *popGesture in VC.navigationController.interactivePopGestureRecognizer.view.gestureRecognizers) {
            popGesture.enabled = NO;
        }
        //若开启全屏右滑，不能再使用下面方法，请对数组进行处理
        //VC.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

+ (void)popGestureOpen:(UIViewController *)VC
{
    // 启用侧滑返回手势
    if ([VC.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
    //这里对添加到右滑视图上的所有手势启用
        for (UIGestureRecognizer *popGesture in VC.navigationController.interactivePopGestureRecognizer.view.gestureRecognizers) {
            popGesture.enabled = YES;
        }
        //若开启全屏右滑，不能再使用下面方法，请对数组进行处理
        //VC.navigationController.                          .enabled = YES;
    }
}

/// 判断字符串是否为空
/// @param string 字符串
+ (BOOL)isBlankString:(NSString *)string
{
    if (!string) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *trimmedStr = [string stringByTrimmingCharactersInSet:set];
    if (!trimmedStr.length) {
        return YES;
    }
    return NO;
}
/// 获取银行卡icon名字
/// @param bankString 银行卡名字
+ (NSString *)getBankICon:(NSString *)bankString
{
    NSString *firstString = @"MY_Bank_Icon_";
    NSDictionary *bankDict = @{
           @"工商银行":@"gongshangyinhang",
           @"农业银行":@"nongyeyinhang",
           @"中国银行":@"zhongguoyinhang",
           @"建设银行":@"jiansheyinhang",
           @"招商银行":@"zhaoshangyinhang",
           @"邮储银行":@"youchuyinhang",
           @"交通银行":@"jiaotongyinhang",
           @"浦发银行":@"pufayinhang",
           @"民生银行":@"minshengyinhang",
           @"兴业银行":@"xingyeyinhang",
           @"平安银行":@"pinganyinhang",
           @"中信银行":@"zhongxinyinhang",
           @"华夏银行":@"huaxiayinhang",
           @"广发银行":@"guangfayinhang",
           @"光大银行":@"guangdayinhang",
           @"农信湖南":@"nongxinhunan",
           @"南京银行":@"nanjingyinhang",
           @"宁波银行":@"ningboyinhang",
           @"汇丰银行":@"huifengyinhang",
           @"花旗银行":@"huaqiyinhang",
           @"东亚银行":@"dongyayinhang",
           @"国家开发银行":@"guojiakaifayinhang",
           @"上海银行":@"shanghaiyinhang",
           @"渣打银行":@"zhadayinhang",
           @"北京银行":@"beijingyinhang",
           @"广州银行":@"guangzhouyinhang",
           @"广州农商银行":@"guangzhounongshangyinhang",
           @"江苏银行":@"jiangsuyinhang",
           @"中国农业发展银行":@"zhongguonongyefazhanyinhang",
           @"中国进出口银行":@"zhongguojinchukouyinhang",
           @"浙商银行":@"zheshangyinhang",
           @"中国人民银行":@"zhongguorenminyinhang",
           @"上海农商银行":@"shanghainongshangyinhang",
           @"重庆农村商业银行":@"chongqingnongcunshangyeyinhang",
           @"北京农商银行":@"beijingnongshangyinhang",
           @"哈尔滨银行":@"haerbinyinhang",
           @"杭州银行":@"hangzhouyinhang",
           @"天津银行":@"tianjinyinhang",
           @"厦门国际银行":@"xiamenguojiyinhang",
           @"中原银行":@"zhongyuanyinhang",
           @"江西银行":@"jiangxiyinhang",
           @"长沙银行":@"changshayinhang",
           @"成都银行":@"chengduyinhang",

       };
//    NSArray *allkey = bankDict.allKeys;
//    for (NSString *key in allkey) {
//        NSLog(@"%@=  MY_Bank_Icon_%@",key,bankDict[key]);
//        NSLog(@"%@=  MY_Bank_Back_%@",key,bankDict[key]);
//
//    }
       NSString *lastString = bankDict[bankString];
       if (!lastString) {
           lastString = @"common";
       }
    return [NSString stringWithFormat:@"%@%@",firstString,lastString];
}
/// 获取银行卡背景图片名字
/// @param bankString 银行卡名字
+ (NSString *)getBankBackImag:(NSString *)bankString
{
    NSString *firstString = @"MY_Bank_Back_";
    NSDictionary *bankDict = @{
        @"工商银行":@"gongshangyinhang",
        @"农业银行":@"nongyeyinhang",
        @"中国银行":@"zhongguoyinhang",
        @"建设银行":@"jiansheyinhang",
        @"招商银行":@"zhaoshangyinhang",
        @"邮储银行":@"youchuyinhang",
        @"交通银行":@"jiaotongyinhang",
        @"浦发银行":@"pufayinhang",
        @"民生银行":@"minshengyinhang",
        @"兴业银行":@"xingyeyinhang",
        @"平安银行":@"pinganyinhang",
        @"中信银行":@"zhongxinyinhang",
        @"华夏银行":@"huaxiayinhang",
        @"广发银行":@"guangfayinhang",
        @"光大银行":@"guangdayinhang",
        @"农信湖南":@"nongxinhunan",
        @"南京银行":@"nanjingyinhang",
        @"宁波银行":@"ningboyinhang",
        @"汇丰银行":@"huifengyinhang",
        @"花旗银行":@"huaqiyinhang",
        @"东亚银行":@"dongyayinhang",
        @"国家开发银行":@"guojiakaifayinhang",
        @"上海银行":@"shanghaiyinhang",
        @"渣打银行":@"zhadayinhang",
        @"北京银行":@"beijingyinhang",
        @"广州银行":@"guangzhouyinhang",
        @"广州农商银行":@"guangzhounongshangyinhang",
        @"江苏银行":@"jiangsuyinhang",
        @"中国农业发展银行":@"zhongguonongyefazhanyinhang",
        @"中国进出口银行":@"zhongguojinchukouyinhang",
        @"浙商银行":@"zheshangyinhang",
        @"中国人民银行":@"zhongguorenminyinhang",
        @"上海农商银行":@"shanghainongshangyinhang",
        @"重庆农村商业银行":@"chongqingnongcunshangyeyinhang",
        @"北京农商银行":@"beijingnongshangyinhang",
        @"哈尔滨银行":@"haerbinyinhang",
        @"杭州银行":@"hangzhouyinhang",
        @"天津银行":@"tianjinyinhang",
        @"厦门国际银行":@"xiamenguojiyinhang",
        @"中原银行":@"zhongyuanyinhang",
        @"江西银行":@"jiangxiyinhang",
        @"长沙银行":@"changshayinhang",
        @"成都银行":@"chengduyinhang",

    };
    NSString *lastString = bankDict[bankString];
    if (!lastString) {
        lastString = @"common";
    }

    return [NSString stringWithFormat:@"%@%@",firstString,lastString];
}
/**
 获取当前VC
 */
+ (UIViewController *)currentVC
{
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
    
    
    return currentVC;
}


+ (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
{
    UIViewController *currentVC;
    
    if ([rootVC presentedViewController]) {
        // 视图是被presented出来的
        
        rootVC = [rootVC presentedViewController];
    }
    
    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        // 根视图为UITabBarController
        
        currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
        
    } else if ([rootVC isKindOfClass:[UINavigationController class]]){
        // 根视图为UINavigationController
        
        currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
        
    } else {
        // 根视图为非导航类
        
        currentVC = rootVC;
    }
    
    return currentVC;
}

/// 设备token
+ (NSData *)deviceToken
{
   return  @"";
}


/// 根据字符串生成高清二维码图片
/// @param codeString 二维码json字符串
/// @param size 二维码大小
+ (UIImage *)QRImage:(NSString *)codeString
              toSize:(CGSize)size
{
    
      //
      NSArray *filters = [CIFilter filterNamesInCategory:kCICategoryBuiltIn];
      NSLog(@"%@",filters);
      
      //二维码过滤器
      CIFilter *qrImageFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
      
      //设置过滤器默认属性 (老油条)
      [qrImageFilter setDefaults];
      
      //将字符串转换成 NSdata (虽然二维码本质上是 字符串,但是这里需要转换,不转换就崩溃)
      NSData *qrImageData = [codeString dataUsingEncoding:NSUTF8StringEncoding];
      
      //我们可以打印,看过滤器的 输入属性.这样我们才知道给谁赋值
      NSLog(@"%@",qrImageFilter.inputKeys);
      /*
       inputMessage,        //二维码输入信息
       inputCorrectionLevel //二维码错误的等级,就是容错率
       */
      
      //设置过滤器的 输入值  ,KVC赋值
      [qrImageFilter setValue:qrImageData forKey:@"inputMessage"];
      
      //取出图片
      CIImage *qrImage = [qrImageFilter outputImage];
      
      //但是图片 发现有的小 (27,27),我们需要放大..我们进去CIImage 内部看属性
//      qrImage = [qrImage imageByApplyingTransform:CGAffineTransformMakeScale(20, 20)];
    
    CGRect extent = CGRectIntegral(qrImage.extent);
    CGFloat scale = MIN(size.width/CGRectGetWidth(extent), size.height/CGRectGetHeight(extent));

    //1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    //创建一个DeviceGray颜色空间
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    //CGBitmapContextCreate(void * _Nullable data, size_t width, size_t height, size_t bitsPerComponent, size_t bytesPerRow, CGColorSpaceRef  _Nullable space, uint32_t bitmapInfo)
    //width：图片宽度像素
    //height：图片高度像素
    //bitsPerComponent：每个颜色的比特值，例如在rgba-32模式下为8
    //bitmapInfo：指定的位图应该包含一个alpha通道。
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    //创建CoreGraphics image
    CGImageRef bitmapImage = [context createCGImage:qrImage fromRect:extent];

    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);

    //2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef); CGImageRelease(bitmapImage);

    //清晰的二维码图片
    UIImage *outputImage = [UIImage imageWithCGImage:scaledImage];
    return outputImage;
}
/**
 生成高清图片(目前主要用在生成二维码哪里)
 
 @param codeString 生成二维码的内容
 @param centerImage 中间logo
 @return image
 
 */
+ (UIImage *)createNonInterpolatedUIImageFormCodeString:(NSString *)codeString withCenterImage:(UIImage *)centerImage
{
    
    
    //
    NSArray *filters = [CIFilter filterNamesInCategory:kCICategoryBuiltIn];
    NSLog(@"%@",filters);
    
    //二维码过滤器
    CIFilter *qrImageFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    //设置过滤器默认属性 (老油条)
    [qrImageFilter setDefaults];
    
    //将字符串转换成 NSdata (虽然二维码本质上是 字符串,但是这里需要转换,不转换就崩溃)
    NSData *qrImageData = [codeString dataUsingEncoding:NSUTF8StringEncoding];
    
    //我们可以打印,看过滤器的 输入属性.这样我们才知道给谁赋值
    NSLog(@"%@",qrImageFilter.inputKeys);
    /*
     inputMessage,        //二维码输入信息
     inputCorrectionLevel //二维码错误的等级,就是容错率
     */
    
    
    //设置过滤器的 输入值  ,KVC赋值
    [qrImageFilter setValue:qrImageData forKey:@"inputMessage"];
    
    //取出图片
    CIImage *qrImage = [qrImageFilter outputImage];
    
    //但是图片 发现有的小 (27,27),我们需要放大..我们进去CIImage 内部看属性
    qrImage = [qrImage imageByApplyingTransform:CGAffineTransformMakeScale(20, 20)];
    
    //转成 UI的 类型
    UIImage *qrUIImage = [UIImage imageWithCIImage:qrImage];
    
    
    //----------------给 二维码 中间增加一个 自定义图片----------------
    //开启绘图,获取图形上下文  (上下文的大小,就是二维码的大小)
    UIGraphicsBeginImageContext(qrUIImage.size);
    CGRect rect = CGRectMake(0, 0, qrUIImage.size.width, qrUIImage.size.height);
   
    //把二维码图片画上去. (这里是以,图形上下文,左上角为 (0,0)点)
    [qrUIImage drawInRect:rect];
    
    
    //再把小图片画上去
   
    
    CGFloat sImageW = 100;
    CGFloat sImageH= sImageW;
    CGFloat sImageX = (qrUIImage.size.width - sImageW) * 0.5;
    CGFloat sImgaeY = (qrUIImage.size.height - sImageH) * 0.5;
     UIImage *sImage = [self getQrCodeCenterImage:centerImage];

    [sImage drawInRect:CGRectMake(sImageX, sImgaeY, sImageW, sImageH)];
    
    //获取当前画得的这张图片
    UIImage *finalyImage = UIGraphicsGetImageFromCurrentImageContext();
    
    //关闭图形上下文
    UIGraphicsEndImageContext();
    
    return finalyImage;
}
+ (UIImage *)getQrCodeCenterImage:(UIImage *)image
{
    UIGraphicsBeginImageContext(image.size);
    CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
    CGContextRef ref = UIGraphicsGetCurrentContext();
    CGContextAddEllipseInRect(ref, rect);
    CGContextClip(ref);
    //把二维码图片画上去. (这里是以,图形上下文,左上角为 (0,0)点)
    [image drawInRect:rect];
    UIImage *crrentImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return crrentImage;
}
/// 当前时间
+ (NSString *)currentDateString:(NSString *)format
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    NSDate *date = [NSDate date];
    NSString *dateString = [dateFormatter stringFromDate:date];
    return dateString;
}

/// 添加登录日志
+ (void)addLoginLog
{
    
}


/// 更新礼物plist
/// @param giftArray 礼物数组
+ (void)updateLiveGiftPlist:(NSArray *)giftArray
{
    
}

/// 获取礼物数组
+ (NSArray *)getLiveGiftPlist
{
    

    return @[];
}




/**
*  判断是否有耳机
*
*  @return 判断是否有耳机
*/
+ (BOOL)hasHeadset {
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    AVAudioSessionRouteDescription *currentRoute = [audioSession currentRoute];
    for (AVAudioSessionPortDescription *output in currentRoute.outputs) {
        if ([[output portType] isEqualToString:AVAudioSessionPortHeadphones]) {
            return YES;
        }
    }
    return NO;
}

+ (void)toShowUpdate:(NSString *)msg forceUpdate:(NSInteger)forceUpdate
{

}


+ (void)isAppStore:(BOOL)isAppStore
{
    
}



/// 去分享
/// @param params 分享内容
+ (void)toShare:(NSDictionary *)params
{
  
}

/// 图片上面编辑文字，主要用来合成短视频水印
/// @param text 文本内容
/// @param image 图片
+ (UIImage*)text:(NSString*)text addToView:(UIImage*)image{
    
    //设置字体样式
    
    UIFont *font = [UIFont systemFontOfSize:15];
    
    NSDictionary *dict = @{NSFontAttributeName:font,NSForegroundColorAttributeName:[UIColor whiteColor]};
    
    CGSize textSize = [text sizeWithAttributes:dict];
    
    //绘制上下文
    
    UIGraphicsBeginImageContext(image.size);
    
    [image drawInRect:CGRectMake(0,0, image.size.width, image.size.height)];
    
    int border =0;
    
    CGRect re = {CGPointMake( border, image.size.height- textSize.height- border), textSize};
    
    //此方法必须写在上下文才生效
    
    [text drawInRect:re withAttributes:dict];
    
    UIImage *newImage =UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return newImage;
    
}
/**
 初始化方法
 @param string 转化字符串
 @param unit 小数点后保留几位

 @param roundingMode 舍入方式{
NSRoundDown,    // Always down == truncate  ／／只舍不入

    NSRoundUp,      // Always up    ／／ 只入不舍

    NSRoundBankers  // on a tie round so last digit is even  貌似四舍五入
}

 @return NSDecimalNumberHandler对象
 */
+ (NSString *)stringCount:(NSString *)string unit:(NSInteger)unit roundingMode:(NSRoundingMode)roundingMode
{
    if (!string || !string.length) {
        return @"";
    }

    NSDecimalNumberHandler *hander = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:roundingMode
                                                                                           scale:unit
                                                                                raiseOnExactness:NO
                                                                                 raiseOnOverflow:NO
                                                                                raiseOnUnderflow:NO
                                                                             raiseOnDivideByZero:NO];
    

    NSDecimalNumber *num = [[NSDecimalNumber decimalNumberWithString:string] decimalNumberByDividingBy :[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"1"]] withBehavior:hander];
    return [NSString stringWithFormat:@"%@",num];

    
}

@end
